import React from 'react';
import { Modal } from 'antd';
import { nextTick } from 'utils/nextTick';
import { combineDate } from 'utils/share';
import moment from 'moment';
import SearchBar from './SearchBar';

class LocationModal extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      isShow: false
    };
    this.onOK = this.onOK.bind(this);
  }

  componentDidMount(){
    const { queryTimeRangeGps, record } = this.props;
    const params = combineDate([ moment(), moment() ]);
    queryTimeRangeGps({ deviceNo: record.equipmentNo, ...params });
  }

  componentWillReceiveProps(next){
    if(typeof next.timeRangeGps !== 'undefined' ||
      next.timeRangeGps !== this.props.timeRangeGps){
      nextTick(() => {
        this.map = new window.BMap.Map('myMap');
        // const { timeRangeGps } = next;
        const timeRangeGps = next.timeRangeGps || [];
        const itArr = [];
        timeRangeGps.forEach(item => {
          const point = new window.BMap.Point(item.longitude, item.latitude);
          itArr.push(point);
        });
        this.setState({ isShow: false });
        if(itArr.length){
          const point = new window.BMap.Point(itArr[0].lng, itArr[0].lat);
          this.map.centerAndZoom(point, 14);
          this.map.enableScrollWheelZoom(true);
          const polyLine = new window.BMap.Polyline(itArr, {
            strokeColor: 'red',
            strokeWeight: 2
          });
          this.map.addOverlay(polyLine);
          this.map.setViewport(itArr);
        }else{
          // message.warning('当日无轨迹');
          this.setState({ isShow: true });
          const point = new window.BMap.Point(116.404, 39.915);
          this.map.centerAndZoom(point, 9);
          this.map.enableScrollWheelZoom(true);
        }
      });
    }
  }

  


  onOK () {
    const { 
      onOK, 
      form,
      onCancel, 
      record,
      getList
    } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        onOK({ ...values, id: record.id }).then(() => {
          onCancel();
          getList();
        });
      }
    });
  }

  render () {
    const {
      record,
      loading,
      onCancel,
      queryTimeRangeGps
     } = this.props;
     const { isShow } = this.state;
    const modalOpts = {
      confirmLoading: loading,
      title: <div>设备轨迹 {isShow && <span style={{marginLeft: 6, fontSize: 12, color: 'red'}}>当日无轨迹</span>}</div>,
      width: 800,
      visible: true,
      maskClosable: false,
      okText: '确定',
      cancelText: '取消',
      onOk: this.onOK,
      onCancel
    };
    const searchProps = {
      record,
      onSearch: queryTimeRangeGps
    };
    return (
      <Modal {...modalOpts}>
        <SearchBar {...searchProps} />
        <div style={{ width: '100%', height: '460px' }} id="myMap" />
      </Modal>
    );
  }
}

export default LocationModal;
